import { useState, useEffect, useCallback } from 'react';

interface UseCarouselOptions {
  totalItems: number;
  autoPlayInterval?: number;
  enableAutoPlay?: boolean;
}

export const useCarousel = ({
  totalItems,
  autoPlayInterval = 5000,
  enableAutoPlay = true,
}: UseCarouselOptions) => {
  const [currentIndex, setCurrentIndex] = useState(0);

  const goToSlide = useCallback((index: number) => {
    if (index >= 0 && index < totalItems) {
      setCurrentIndex(index);
    }
  }, [totalItems]);

  const goToPrevious = useCallback(() => {
    setCurrentIndex((prevIndex) =>
      prevIndex === 0 ? totalItems - 1 : prevIndex - 1
    );
  }, [totalItems]);

  const goToNext = useCallback(() => {
    setCurrentIndex((prevIndex) =>
      prevIndex === totalItems - 1 ? 0 : prevIndex + 1
    );
  }, [totalItems]);

  useEffect(() => {
    if (!enableAutoPlay || totalItems <= 1) return;

    const interval = setInterval(goToNext, autoPlayInterval);
    return () => clearInterval(interval);
  }, [enableAutoPlay, autoPlayInterval, totalItems, goToNext]);

  return {
    currentIndex,
    goToSlide,
    goToPrevious,
    goToNext,
  };
};